 
var pageContext = new PageContextJqgrid(settings||{});
pageContext.setting.canShowPower = true;
pageContext.setting.canUpdatePower = true;
pageContext.setting.canPage = false;

var pageContextTree = new PageContextTree(settings||{});
pageContextTree.removeItemAfter = function(ids){
	 if(!isNaN(ids)){
		 pageContext.setDeleteClass($("#"+pageContext.setting.tableId+"_tr_"+ids),true);
	 }else{
		var array = ids.split(",");
		for (x in array)
		{
			var id = array[x];
			pageContext.setDeleteClass($("#"+pageContext.setting.tableId+"_tr_"+id),true);
		}
	}
}; 	

pageContext.formInit = function(layero,index,type){
	layero.find('select').each(function(){
		var novalid = $(this).attr("novalid");
		if(novalid!="true"){
			try {
				//$(this).select2();
			} catch (e) {
				console.log(e)
			}
		}
	  });
}; 	
pageContext.renderAddPageOther = function(layero,data,option){
	var name = "pId";
	var nodes = pageContextTree.getSelectedNodes();
	var selected = false;
	for(index in nodes){
		var node = nodes[index];
		if(node){
			var value = node.id;
			layero.find("span[name='pName']").text(node.name);
			layero.find("input[name='"+name+"']").attr("oldval",value).val(value);
			tvc.changeDefaultValue(layero.find("input[name='"+name+"']").get(0));
		}
	}
};
pageContext.renderUpdatePageOther = function(layero,data,option){
	var name = "pId";
	var value = data.pId;
	var node = pageContextTree.getNode(value);
	if(node){
		layero.find("span[name='pName']").text(node.name);
		layero.find("input[name='"+name+"']").attr("oldval",value).val(value);
		layero.find("input[name='remark']").attr("oldval",node.remark).val(node.remark);
		tvc.changeDefaultValue(layero.find("input[name='"+name+"']").get(0));
	}
	var value = data.id;
	var node = pageContextTree.getNode(value);
	if(node){
		layero.find("input[name='remark']").attr("oldval",node.remark).val(node.remark);
	}
};
  
/**组织树**/  
var tree_setting = {
		async: {
			enable: true,
			type: "get",
			url: window.global.getFinalUrl(window.global.ctx+"/str/table/tree?_style=list"),
			otherParam: {'hasInstance':window.global.hasInstance,"noPage":"true"},
		},
		view: {
			addHoverDom: null,
			removeHoverDom: null,
			selectedMulti: false
		},
		check: {
			enable: false
			,chkboxType :{ "Y" : "", "N" : "" } 
		},
		data: {
			simpleData: {
				enable: true
			}
			,key: {
				url: ""
				,title: "title"
			}
		} 
		,edit: {
			enable: false,
			editNameSelectAll: true,
			showRemoveBtn: null,
			showRenameBtn: null
		}
		,callback: {
			 onClick: zTreeOnClick,
			 beforeClick: zTreeBeforeClick
		}
};
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
	var $num = $("#searchForm").find("input[name='tableId']")
	var num = $num.val();
	var node  = pageContextTree.getNodeFromParent("tableId",num,treeNode)
	if(node){
		pageContextTree.selectNode(node.id);
	}else{
		$num.val("");
	}
};
function zTreeBeforeClick(treeId, treeNode, clickFlag) {
    return (treeNode.type=="table");
};
function zTreeOnClick(event, treeId, treeNode) {
	if(treeNode.type!="table"){
		return false;
	}
	$(".searchBtn").attr("disabled",false);
	$("#searchForm").find("input[name='tableId']").val(treeNode.id);
	$("#idTypeCode").val(treeNode.idTypeCode);
	pageContext.selectRow(treeNode)
	pageContext.search();
	return true;
};
var i = 0;
var $selectName=null;
pageContext.selectRow = function(node){
	$("#tableId").val(node.id);
	  colNames = [];
	  colModel = [];
	  colSysModel = [];
	var data = {id:$("#tableId").val()}
	$.get(window.global.ctx+"/str/data/fields",data, function(result) {
		if(result.status==200){
			var list = result.data;
			if(pageContext.setting.canUpdate || pageContext.setting.canDelete){
				colNames.push('操作');
				colModel.push({name:'',index:'',align:"center"
					, width:80, fixed:true
					, sortable:false, resize:false, editable: false,
					formatter:'actions', 
					formatoptions:{ 
						onEdit: op.onEdit,
						onSuccess: op.successfunc,
						aftersavefunc: op.aftersavefunc,
						errorfunc: op.errorfunc,
						keys:true,
						extraparam:{tableId:$("#tableId").val()},
						editbutton:pageContext.setting.canUpdate ||pageContext.setting.canAdd, 
						editformbutton: false,
						delbutton:pageContext.setting.canDelete,
					    delOptions: { delData:{tableId:$("#tableId").val()},recreateForm: true, beforeShowForm: beforeDeleteCallback }
					}
				});
			}
			colNames.push('hbase');
			colModel.push({name:"p."+hidenField,index:"p."+hidenField
					, hidden:true
			});
			var $fieldName = $("#fieldName");
			$fieldName.empty();
			$fieldName.append("<option value=''>--字段--</option>")
			for(index in list){
				var f = list[index];
				if(f.createdIndex){
					$fieldName.append("<option value='p."+f.indexName+"'>"+f.nameCn+"</option>")
				}
				colNames.push(f.nameCn);
				
				var name = f.realName;
				var model =  {name:"p."+name,index:"p."+f.indexName, width:60
						, sorttype:f.fieldType
						, editable: pageContext.setting.canUpdate || pageContext.setting.canAdd
						};
				model.editrules={};
				model.editrules={required:!f.isNull};
				if("boolean"==f.fieldType || "booleanx"==f.fieldType){
					model.edittype="select";
					model.editoptions={value:":未知;true:是;false:否"};
				}else if("integer"==f.fieldType || "short"==f.fieldType
						 || "long"==f.fieldType|| "byte"==f.fieldType){
					model.editrules.integer=true;
				}else if("number"==f.fieldType || "double"==f.fieldType
						 || "float"==f.fieldType){
					model.editrules.number=true;
				}else if("date"==f.fieldType){
					model.editrules.date=true;
					model.unformat=pickDate;
				}else if("datetime"==f.fieldType){
					model.unformat=pickDateTime;
				}else if("datetimelong"==f.fieldType){
					model.unformat=pickDateTime;
				}else if("time"==f.fieldType){
					model.unformat=pickTime;
				}else if("timestamp"==f.fieldType){
					model.unformat=pickDateTime;
				}else if("timestamplong"==f.fieldType){
					model.unformat=pickDateTime;
				}
				if(f.fieldLen && f.fieldLen>100){
					model.edittype="textarea";
					model.editoptions = {rows:"2",cols:"10"};
				}
				if("text"==f.fieldType){
					model.edittype="textarea";
					model.editoptions = {rows:"2",cols:"10"};
				}
				if(true==f.primaryKey && true==f.sysClass){
					model.key=true;
					model.editable = false;
					if($("#idTypeCode").val()=="0" && "_sys_id"==f.name){
						model.editable=true;
					}
				}
				if(true!=f.primaryKey && true==f.sysClass){
					model.editrules.required = false;
				}
				if(true==f.createdIndex){
					model.search=true;
				}else{
					model.search=false;
				}
				if(true==f.sysClass){
					model.hidden=true;
					if($("#idTypeCode").val()=="0" && "_sys_id"==f.name){
						model.hidden=false;
					}else{
						colSysModel.push("p."+name)
					}
				}
				colModel.push(model);
			}
			var option = {
					colNames:colNames,
					colModel:colModel,
					search:false,
					url:window.global.getFinalUrl(window.global.ctx+"/str/data/query?_style=jq&tableId="+$("#tableId").val()),
					width:$("#searchTableDiv").width(),
//					rownumWidth:"",
//					data: grid_data,
//					datatype: "local",

				    loadError: function(xhr,status,error){  
				       //alert(status + " loading data of " + $(this).attr("id") + " : " + error );   
				     },
					delOptions:{
						delData:{tableId:$("#tableId").val()},
						afterSubmit: del.deleteItemAfter
					},
					ondblClickRow : function(rowid,iRow,iCol,e) {
				          if (rowid ) {
//				        	jQuery(pageContext.grid_selector).jqGrid('restoreRow', lastsel);
				        	pageContext.toEdit(rowid);
				        	lastsel = rowid;
				          }
				    }
			}
			if(!pageContext.setting.canUpdate){
				option.ondblClickRow = null;
			}
			console.log(i)
			if(i>0){
				$("#fieldName").select2("destroy")
				$selectName=$("#fieldName").select2({language: "zh-CN",placeholder: "字段",width: "150px"})
				$.jgrid.gridUnload("#searchTable"); 
				pageContext.resetGrid(option);
			}else{
				$selectName=$("#fieldName").select2({language: "zh-CN",placeholder: "字段",width: "150px"})
				pageContext.init(option);
			}
			setTimeout(function(){
				$("#alertmod_"+pageContext.setting.tableId).remove();
			},500)
			i++;
		}
	});
}
pageContextTree.reload = function(){
	var nodes = pageContextTree.getNodesFromParent("type","instance",null)
	if(nodes && nodes.length>0){
		pageContextTree.hasInstance = true;
		for(var i in nodes){
			var obj = nodes[i];
			pageContextTree.treeObj.reAsyncChildNodes(obj, "refresh");
		}
	}else{
		pageContextTree.treeObj.reAsyncChildNodes(null, "refresh");
	}
}
pageContextTree.load = function(){
	var distSys = false;
	if(distSys){
	 
	}else{
		pageContextTree.initTree($("#treeForm"+" .ztree"),null, tree_setting )
	}
}
/**
 * 渲染tree
 */
pageContext.afterRenderGrid = function(gridData){
	 if(!pageContext.passiveInvoke){
		 pageContextTree.reload();
	 }
	 pageContext.passiveInvoke = true;
	 pageInit();
};
pageContext.resetAfter = function(){ 
	$selectName.val(null).trigger("change");
};
var index =0;
function otherPageInit(iframe){
	index++;
		console.log()
		var th = $(window.top).height();
		var h = document.body.clientHeight;
		console.log("h:"+h)
		h = h-$("#treeDiv").offset().top-10;
		console.log("otherPageInit")
		console.log("h:"+h)
		console.log("th:"+th)
		console.log("iframe.offset().top:"+iframe.offset().top)
		th = th-iframe.offset().top;
		console.log("th:"+th)
		$("#treeDiv").height(Math.max(h,th-75));
		window.global.iframeHeight(iframe,Math.max(h+75,th));
		var th = top.document.body.clientHeight;
		console.log("th:"+th)
}
var size = 0;
var colNames = [];
var colModel = [];
var colSysModel = [];
var lastsel = null;
var op = {};
op.onEdit=function(res){
	console.log(res)
};
op.successfunc=function(res){
	console.log(res)
	console.log(res.responseJSON)
	return true;
};
op.aftersavefunc=function(rowid, res, tmp, o){
	console.log(rowid)
	console.log(res)
	console.log(tmp)
	console.log(o)
};
op.errorfunc=function(rowid, res, stat,err){
	console.log(rowid)
	console.log(res)
	console.log(stat)
	console.log(err)
};
var del={
};
del.deleteItemAfter = function(data,postd){
	  console.log(data)
	  console.log(postd)
	  pageContext.deleteItemAfter();
	  return [true,""];
};

var hidenField = "_hiden_rowkey_s";
var prefix = "p.";
var priKey = prefix+hidenField;
var hideSys = true;

function getWindowSize(){
	var size = {};
	//获取窗口宽度
	if(window.innerWidth){    //兼容火狐，谷歌,safari等浏览器
		size.width=window.innerWidth;
		}
	else if((document.body)&&(document.body.clientWidth)){    //兼容IE浏览器
		size.width=document.body.clientWidth;
		}
	
	//获取窗口高度
	if(window.innerHeight){
		size.height=window.innerHeight;
	}
	else if((document.body)&&(document.body.clientHeight)){
		size.height=document.body.clientHeight;
	}
	return size;
};
$(function(){
	pageContextTree.load();
	init();
	$("#reload_tree").on("click",function(){
		pageContextTree.treeObj.reAsyncChildNodes(null, "refresh");
	});
})
function init(){
    //resize to fit page size
	$(window).on('resize.jqGrid', function () {
		$("#searchTable").jqGrid( 'setGridWidth',$("#searchTableDiv").width());
    })
	$('.toolbar .hideBtn').on("click", function (e) {
		 e.preventDefault();
		 var me = $(this);
		 var val = me.attr("val");
		 var hide = true;
		 if(val=="0"){
			 val = "1";
			 hide = false;
			 hideSys = false;
			 me.find("i").html("隐藏系统字段")
		 }else{
			 val = "0";
			 hideSys = true;
			 me.find("i").html("显示系统字段")
		 }
		 if(hide){
			 jQuery("#searchTable").jqGrid("hideCol",colSysModel).jqGrid("setGridWidth",$("#searchTableDiv").width());
		 }else{
			 jQuery("#searchTable").jqGrid("showCol",colSysModel).jqGrid("setGridWidth",$("#searchTableDiv").width());
		 }
		 me.attr("val",val);
		return false;
	 }); 
	$("#gridHeightUp").on("click",function(){
		$("#"+pageContext.setting.tableId).addGridHeight(5);
		//$("body").height($("body").height()+5);
		//parent.iframeTab.iframeAddHeight(5);
		
	});
	$("#gridHeightDown").on("click",function(){
		$("#"+pageContext.setting.tableId).addGridHeight(-5);
		//$("body").height($("body").height()-5);
		//parent.iframeTab.iframeAddHeight(-5);
	});
	
	$("#fieldName").on("change",function(){
		var val = $(this).val();
		$("#fieldValue").attr("name",val);
	});
}
function beforeDeleteCallback(e) {
	console.log("beforeDeleteCallback")
	console.log(e)
	var form = $(e[0]);
	if(form.data('styled')) return false;
	
	form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
	style_delete_form(form);
	
	form.data('styled', true);
}
